package com.study.book.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.study.book.common.AuthenticationRequired;
import com.study.book.common.R;
import com.study.book.mapper.AdminMapper;
import com.study.book.pojo.Admin;
import com.study.book.utils.IpUtils;
import com.study.book.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;


@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtUtils jwtutils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断方法是否需要认证
            if (method.isAnnotationPresent(AuthenticationRequired.class)) {
                AuthenticationRequired annotation = method.getAnnotation(AuthenticationRequired.class);
                // 读取 value 参数
                String value = annotation.value();

                // 判断用户是否认证
                if (!isUserAuthenticated(request,value)) {
                    // 未认证，重定向到登录页面
                    String ipAddr = IpUtils.getIpAddr(request);
                    log.error(ipAddr);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=utf-8");
                    // 构建返回结果对象
                    String errorMsg = new ObjectMapper().writeValueAsString(R.error(-1, "认证失败，请登录"));

                    // 写入响应并关闭资源
                    PrintWriter out = response.getWriter();
                    out.print(errorMsg);
                    out.flush();
                    out.close();
                    return false; // 终止后续处理
                }
            }
            if(request.getRequestURI().startsWith("/app/Mange/") && !request.getRequestURI().equals("/app/Mange/login"))
            {
                String token = request.getHeader("Authorization");
                String extractUsername = jwtutils.extractUsername(token);
                request.setAttribute("type",extractUsername.substring(0,1));
                request.setAttribute("userId",extractUsername.substring(1));
                return true; // 放行其他请求
            }
        }
        return true; // 放行其他请求
    }


    @Autowired
    private AdminMapper adminMapper;

    private boolean isUserAuthenticated(HttpServletRequest request, String value) {
        String token = request.getHeader("token");
        if (!Strings.isEmpty(token)) {
            String extractUsername = jwtutils.extractUsername(token);
            Admin admin = adminMapper.selectById(extractUsername);
            if (admin.getType().equals(value)) {
                request.setAttribute("userId", extractUsername);
                return true; // 假设认证通过
            }
        }
        return false; // 假设认证失败
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //  System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // System.out.println("afterCompletion");

    }
}
